<template>
    <div class="scroll-container">
        <div v-if="loading" class="status-message">加载中...</div>
        <div v-else-if="errorMessage" class="status-message error">{{ errorMessage }}</div>
        <div v-else-if="!contacts.length" class="empty-tips">
            <div class="empty-icon">📭</div>
            <div class="empty-text">当前通讯录为空，请导入数据</div>
        </div>
        <div v-show="contacts.length" class="contact-list">
            <div v-for="(contact, index) in filteredContacts" :key="index" class="contact-item flex-box flex-acenter">
                <div class="contact-field flex2">序号：{{ index + 1 }}</div>
                <div class="contact-field copy flex2" @click="copyField(contact, '姓名')">姓名：{{ contact.姓名 || '未填写' }}</div>
                <div class="contact-field copy flex3" @click="copyField(contact, '电话')">电话：{{ contact.电话 || '未填写' }}</div>
                <div class="contact-field flex3">职位：{{ contact.职位 || '未填写' }}</div>
                <div class="contact-field flex4">邮箱：{{ contact.邮箱 || '未填写' }}</div>
                <div class="contact-actions">
                    <button @click="copyAll(contact)">复制全部</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { showDialog } from 'vant';
import { ref, onMounted, computed } from 'vue';
import pinyin from 'pinyin';
const contacts = ref([]);
const searchKeyword = ref('');

onMounted(() => {
    loadContacts();
});

const loadContacts = async () => {
    // 从数据库读取联系人数据
    try {
        const doc = await window.utools.db.promises.get('contacts');
        if (doc && doc.data) {
            contacts.value = doc.data;
            console.log('数据库读取成功:', doc);
        } else {
            console.log('数据库无联系人数据');
        }
    } catch (err) {
        console.error('数据读取失败:', err);
    }
};

const filteredContacts = computed(() => {
    if (!searchKeyword.value) {
        return contacts.value;
    }

    const kw = searchKeyword.value.toLowerCase();
    const isPhoneSearch = /^\d+$/.test(kw);
    const isInitialsSearch = /^[a-z]+$/.test(kw);

    return contacts.value.filter((contact) => {
        if (isPhoneSearch) {
            return String(contact.电话 || '')
                .toLowerCase()
                .includes(kw);
        }

        if (isInitialsSearch) {
            const name = contact.姓名 || '';
            const initials = pinyin(name, {
                style: pinyin.STYLE_FIRST_LETTER, // 精确到每个字的首字母
                heteronym: false // 关闭多音字模式
            })
                .flat()
                .join('')
                .toLowerCase();
            return initials.startsWith(kw);
        }

        return [contact.姓名, contact.职位].some((field) =>
            String(field || '')
                .toLowerCase()
                .includes(kw)
        );
    });
});

const copyAll = (contact) => {
    try {
        const text = `姓名：${contact.姓名 || ''}
电话：${contact.电话 || ''}
职位：${contact.职位 || ''}
邮箱：${contact.邮箱 || ''}`;

        navigator.clipboard.writeText(text);
        showDialog({
            title: '温馨提示',
            message: '已复制全部信息'
        });
    } catch (err) {
        console.error('复制失败:', err);
    }
};

const copyField = (contact, field) => {
    try {
        const value = contact[field] || '';
        const displayValue = value || `无${field}信息`;
        navigator.clipboard.writeText(value);
        showDialog({
            title: '温馨提示',
            message: `已复制${field}：${displayValue}`
        });
    } catch (err) {
        console.error('复制失败:', err);
    }
};

utools.setSubInput(({ text }) => {
    searchKeyword.value = text;
}, '搜索');
</script>

<style scoped>
.scroll-container {
    padding: 10px;
}

.contact-item {
    padding: 5px;
    border-bottom: 1px solid #eee;
}

.contact-actions button {
    margin-left: 8px;
    padding: 6px 12px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.contact-field.copy {
    cursor: pointer;
    transition: background-color 0.2s;
}

.contact-field:hover {
    background-color: #f5f5f5;
}

.empty-tips {
    padding: 40px 20px;
    text-align: center;
    color: #888;
}
.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}
.empty-text {
    font-size: 14px;
}
</style>
